import React, { useEffect, useState, useRef } from "react";
import HeaderNav from "@/components/header-nav";
import styles from "./index.module.less";
import classNames from "classnames";
const { getMemberRights } = $globalServicer("My");
import { CheckCircleFill } from "antd-mobile-icons";
import { Button, Loading } from "antd-mobile";

const MyRights = () => {
  const [membershipData, setMembershipData] = useState([]);
  const [loading, setLoading] = useState(true);
  const customNavigate = $globalNavigate();

  useEffect(() => {
    const getMemberRightsData = async () => {
      try {
        setLoading(true);
        const response = await getMemberRights();
        setMembershipData(response);
      } catch (error) {
        console.error('获取会员权益失败:', error);
        setMembershipData([]);
      } finally {
        setLoading(false);
      }
    };
    getMemberRightsData();
  }, []);

  const renderFeatureItem = (label, value, isHighlight = false) => (
    <div className={styles.featureItem}>
      <span className={styles.featureLabel}>{label}:</span>
      <span
        className={classNames(styles.featureValue, {
          [styles.highlight]: isHighlight,
        })}
      >
        {value}
      </span>
    </div>
  );

  // 获取进度条颜色的函数
  const getProgressColor = (percentage) => {
    if (percentage <= 25) {
      return "#52c41a"; // 绿色 - 充足
    } else if (percentage <= 50) {
      return "#1890ff"; // 蓝色 - 良好
    } else if (percentage <= 75) {
      return "#faad14"; // 黄色 - 正常
    } else if (percentage <= 90) {
      return "#fa8c16"; // 橙色 - 警告
    } else {
      return "#f5222d"; // 红色 - 危险
    }
  };

  // 获取进度条渐变颜色
  const getProgressGradient = (percentage) => {
    const baseColor = getProgressColor(percentage);
    if (percentage <= 25) {
      return `linear-gradient(90deg, #52c41a, #73d13d)`;
    } else if (percentage <= 50) {
      return `linear-gradient(90deg, #1890ff, #40a9ff)`;
    } else if (percentage <= 75) {
      return `linear-gradient(90deg, #faad14, #ffc53d)`;
    } else if (percentage <= 90) {
      return `linear-gradient(90deg, #fa8c16, #ff9c6e)`;
    } else {
      return `linear-gradient(90deg, #f5222d, #ff4d4f)`;
    }
  };

  // 获取使用状态描述
  const getUsageStatusText = (percentage) => {
    if (percentage <= 25) {
      return "使用充足";
    } else if (percentage <= 50) {
      return "使用良好";
    } else if (percentage <= 75) {
      return "使用正常";
    } else if (percentage <= 90) {
      return "即将用完";
    } else {
      return "使用告急";
    }
  };

  const renderProgressBar = (used, total) => {
    const percentage = (used / total) * 100;
    const progressColor = getProgressColor(percentage);
    const progressGradient = getProgressGradient(percentage);
    const statusText = getUsageStatusText(percentage);
    if (total === 0) {
      return (
      <div className={styles.progressContainer}>
      <div className={styles.progressBar}>
        <div
          className={styles.progressFill}
          style={{
            width: `0%`,
            background: 'linear-gradient(90deg, #52c41a, #73d13d)',
          }}
        ></div>
      </div>
      <div className={styles.progressLabel}>
        <span className={styles.statusText} style={{ color: "#666" }}>
          使用充足
        </span>
        <span
          className={styles.percentageText}
          style={{ color: 'linear-gradient(90deg, #52c41a, #73d13d)' }}
        >
          0%
        </span>
      </div>
    </div>
      )
    }
    return (
      <div className={styles.progressContainer}>
        <div className={styles.progressBar}>
          <div
            className={styles.progressFill}
            style={{
              width: `${percentage}%`,
              background: progressGradient,
            }}
          ></div>
        </div>
        <div className={styles.progressLabel}>
          <span className={styles.statusText} style={{ color: "#666" }}>
            {statusText}
          </span>
          <span
            className={styles.percentageText}
            style={{ color: progressColor }}
          >
            {percentage.toFixed(1)}%
          </span>
        </div>
      </div>
    );
  };
  const renderBenefits = (benefits) => {
    if (!benefits) return null;
    if (benefits.length === 0) return null;
    let _benefits = [];
    if (benefits?.length && benefits.indexOf("\r\n")) {
      _benefits = benefits.split("\r\n");
    } else {
      _benefits = [benefits];
    }
    return (
      <div className={styles.vipBenefits}>
        {_benefits?.map((g, _index) => (
          <div className={styles.benefitItem} key={_index}>
            <CheckCircleFill className={styles.checkIcon} />
            <span key={_index}>{g}</span>
          </div>
        ))}
      </div>
    );
  };
  const getExpirationTime = (expirationTime) => {
    if (expirationTime === null) return "🟢 永久有效";
    // 需要将 expirationTime 转换为 时间戳然后和当前时间比较。
    let _expirationTime = new Date(expirationTime).getTime();
    if (_expirationTime < Date.now()) return "🔴 已过期";
    return `🔵 有效期至: ${expirationTime}`;
  };

  // 获取状态对应的颜色和背景色
  const getStatusStyle = (expirationTime) => {
    if (expirationTime === null) {
      return {
        color: "#52c41a",
        backgroundColor: "#f6ffed",
        borderColor: "#b7eb8f",
      };
    }

    let _expirationTime = new Date(expirationTime).getTime();
    if (_expirationTime < Date.now()) {
      return {
        color: "#f5222d",
        backgroundColor: "#fff1f0",
        borderColor: "#ffccc7",
      };
    }

    return {
      color: "#1890ff",
      backgroundColor: "#f0f9ff",
      borderColor: "#91d5ff",
    };
  };

  const renderMembershipCard = (membership) => (
    <div key={membership.id} className={styles.membershipCard}>
      {/* 会员头部信息 */}
      <div
        className={styles.membershipHeader}
        // "linear-gradient(135deg, #c0c0c0, #e6e6e6)"
        style={{
          background:
            membership.type === 1
              ? "linear-gradient(to right, #f9c27a, #f9a26c)"
              : "linear-gradient(to right, #a18cd1, #aaa1f7)" ||
                "linear-gradient(135deg, #ffd700, #ffed4a)",
        }}
      >
        <div className={styles.membershipTitle}>
          <h3>{membership.title}</h3>
          <div className={styles.validPeriod}>
            {getExpirationTime(membership.level_expiration_time)}
          </div>
        </div>
        <div className={styles.membershipIcon}>
          {
            membership.type === 0 ? (
              <div className={styles.crownIcon}>🆓</div>
            ) : (
              <div className={styles.crownIcon}>👑</div>
            )
          }
        </div>
      </div>

      {/* 权益详情 */}
      <div className={styles.membershipDetails}>
        {/* {renderFeatureItem("开通期限", membership.features.开通期限)}
                {renderFeatureItem("充值折扣", membership.features.充值折扣)}
                {renderFeatureItem("消耗折扣", membership.features.消耗折扣)}
                {renderFeatureItem("专属模式", membership.features.专属模式)}
                {renderFeatureItem("记忆力提升倍数", membership.features.记忆力提升倍数)}
                {renderFeatureItem("专属AI响应速度", membership.features.专属AI响应速度)}
                {renderFeatureItem("免费模型", membership.features.免费模型)}
                {renderFeatureItem("限时活动赠送", membership.features.限时活动赠送, true)} */}
        {renderBenefits(membership?.benefits)}
        {/* {membership.specialNote && (
                    <div className={styles.specialNote}>
                        <strong>特殊备注:</strong> {membership.specialNote}
                    </div>
                )} */}
      </div>

      {/* 模型使用情况 */}
      {membership?.member_right?.map((item, index) => (
        <div className={styles.modelUsage} key={item.id}>
            <div className={styles.modelUsageWrapper}>

          <div className={styles.modelHeader}>
            <div className={styles.modelInfo}>
              <span className={styles.modelName}>
               {item.model.name}
              </span>
            </div>
            
          </div>
          <div className={styles.usageInfo}>
            <span
                className={styles.modelStatus}
                style={getStatusStyle(item.userRight.expiry_date)}
              >
                {getExpirationTime(item.userRight.expiry_date)}
              </span>
            </div>
          <div className={styles.usageStats}>
            {
              membership.type === 0 ? (
                <span className={styles.usageNumbers}>
                  <strong>{item.userRight.used_count}</strong> / {item.userRight.is_model_unlocked === 1 ? '无限制' : item.usage_count}{" "}
                  次
                </span>
              ) : (
                <span className={styles.usageNumbers}>
                  <strong>{item.userRight.used_count}</strong> / {item.usage_count === 0 ? '无限制' : item.usage_count}{" "}
                  次
                </span>
              )
            }
          </div>
          { membership.type === 0 && item.userRight.is_model_unlocked === 1 ? renderProgressBar(item.userRight.used_count, 0):renderProgressBar(item.userRight.used_count, item.usage_count)}
          {/* {item.userRight.expiry_date && (
                    <div className={styles.modelExpiration}>
                        <span className={styles.expirationLabel}>有效期至:</span>
                        <span className={styles.expirationDate}>{item.userRight.expiry_date}</span>
                    </div>
                )} */}
        </div>
        </div>

      ))}
    </div>
  );

  return (
    <div className={styles.myRightsContainer}>
      <HeaderNav title="会员权益" />
      <div className={styles.content}>
        {loading ? (
          <div className={styles.loadingContainer}>
            <Loading size="large" />
            <div className={styles.loadingText}>正在加载会员权益...</div>
          </div>
        ) : membershipData.length ? (
          membershipData.map((membership) => renderMembershipCard(membership))
        ) : (
          <div className={styles.notRight}>
            <div className={styles.emptyIcon}>👑</div>
            <div className={styles.emptyTitle}>暂无会员权益</div>
            <div className={styles.emptyDesc}>开通会员享受更多专属特权</div>
            <Button 
              color="primary" 
              fill="solid" 
              size="large"
              className={styles.openVipBtn}
              onClick={() => customNavigate("/recharge")}
            >
              立即开通会员
            </Button>
          </div>
        )}
      </div>
    </div>
  );
};

export default MyRights;
